package com.jwell.panprovider.presenter

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.jwell.driverapp.tools.BaseSubscriber
import com.jwell.driverapp.ui.base.BasePresenter
import com.jwell.panprovider.contract.WaybillListContract
import com.jwell.panprovider.entity.ForExportWaybillListDto
import com.jwell.panprovider.entity.WaybillListBean
import com.jwell.panprovider.model.WaybillListModel
import org.json.JSONObject
import org.reactivestreams.Subscription

/**
 * Created by 76577 on 2018/6/19.
 * 运单管理
 */
class WaybillListPresenter : BasePresenter<WaybillListContract.View>(), WaybillListContract.Presenter {
    private var mySearchData: WaybillListModel.RequestData? = null
    private val mode: WaybillListModel by lazy {
        WaybillListModel()
    }

    override fun fresh() {
        super.fresh()
        mySearchData?.let {
            searchListData(it)
        }
    }

    override fun load() {
        super.load()
        mySearchData?.let {
            searchListData(it)
        }
    }

    override fun searchListData(searchData: WaybillListModel.RequestData) {
        if (searchData.skipCount == 0) {
            index = 0
        }
        searchData.maxResultCount = maxResult
        searchData.skipCount = maxResult * index
        mySearchData = searchData
        mode.searchListData(searchData, object : BaseSubscriber() {
            override fun setSubscription(s: Subscription) {
                mSubscription = s
            }

            override fun succeed(data: JSONObject) {
                getView()?.hideProgress()
                val result = data.getJSONObject("result")
                getView()?.setSearchTotalCount(result.getInt("totalCount"))
                val beanList = Gson().fromJson<List<WaybillListBean>>(result.getString("items"), object : TypeToken<List<WaybillListBean>>() {
                }.type)
                if (index == 0) {
                    getView()?.showListData(beanList, true)
                } else {
                    getView()?.showListData(beanList, false)
                }
                index++
                mySearchData?.skipCount = maxResult * index
            }

            override fun onFailed(msg: String) {
                getView()?.hideProgress()
                getView()?.setSearchTotalCount(0)
                if (index == 0) {
                    getView()?.showListDataFailed(true, msg)
                } else {
                    getView()?.showListDataFailed(false, msg)
                }
            }
        })
    }
}